package com.minimalist.lindi.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.lang.Assert;
import cn.hutool.http.HttpStatus;
import com.minimalist.common.config.exception.BusinessException;
import com.minimalist.common.config.mybatis.bo.PageResp;
import com.minimalist.common.entity.basic.vo.file.FileVO;
import com.minimalist.common.entity.lindi.po.LindiTradeApplicationConfirmLetter;
import com.minimalist.common.entity.lindi.vo.tradeapplicationconfirmletter.LindiTradeApplicationConfirmLetterQueryVO;
import com.minimalist.common.entity.lindi.vo.tradeapplicationconfirmletter.LindiTradeApplicationConfirmLetterVO;
import com.minimalist.common.feign.client.basic.FileFeignClient;
import com.minimalist.common.response.R;
import com.minimalist.common.utils.UnqIdUtil;
import com.minimalist.lindi.mapper.LindiTradeApplicationConfirmLetterMapper;
import com.minimalist.lindi.service.LindiTradeApplicationConfirmLetterService;
import com.mybatisflex.core.paginate.Page;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

/**
 * 林地指标交易平台_交易申请确认函 服务层实现。
 *
 * @author 11987
 * @since 2025-06-06
 */
@Service
public class LindiTradeApplicationConfirmLetterServiceImpl extends ServiceImpl<LindiTradeApplicationConfirmLetterMapper, LindiTradeApplicationConfirmLetter> implements LindiTradeApplicationConfirmLetterService{

    private static final Logger logger = LoggerFactory.getLogger(LindiTradeApplicationConfirmLetterServiceImpl.class);

    @Autowired
    private LindiTradeApplicationConfirmLetterMapper mapper;

    @Autowired
    private FileFeignClient fileFeignClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void addTradeApplicationConfirmLetter(LindiTradeApplicationConfirmLetterVO tradeApplicationConfirmLetterVO){
        LindiTradeApplicationConfirmLetter confirmLetter = new LindiTradeApplicationConfirmLetter();
        BeanUtil.copyProperties(tradeApplicationConfirmLetterVO, confirmLetter);
        confirmLetter.setConfirmLetterId(UnqIdUtil.uniqueId());
        confirmLetter.setCreateId(tradeApplicationConfirmLetterVO.getCreateId());
        confirmLetter.setUpdateId(tradeApplicationConfirmLetterVO.getUpdateId());
        confirmLetter.setCreateTime(tradeApplicationConfirmLetterVO.getCreateTime());
        confirmLetter.setUpdateTime(tradeApplicationConfirmLetterVO.getUpdateTime());

        int insert = mapper.insert(confirmLetter, true);
        Assert.isTrue(insert == 1, () -> new BusinessException("添加交易申请确认函失败"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTradeApplicationConfirmLetterByConfirmLetterId(Long confirmLetterId){
        LindiTradeApplicationConfirmLetter confirmLetter = mapper.selectTradeApplicationConfirmLetterByConfirmLetterId(confirmLetterId);
        Assert.notNull(confirmLetter, () -> new BusinessException("交易申请确认函不存在"));

        // 删除关联的文件
        if (confirmLetter.getFileId() != null){
            try{
                R<Void> result = fileFeignClient.deleteFile(confirmLetter.getFileId());
                if (result.getCode() != 200){
                    logger.warn("删除确认函文件失败，文件ID: {}, 错误信息: {}", confirmLetter.getFileId(), result.getMessage());
                }
            } catch (Exception e){
                logger.warn("删除确认函文件异常，文件ID: {}, 异常信息: {}", confirmLetter.getFileId(), e.getMessage());
            }
        }

        int delete = mapper.delete(confirmLetter);
        Assert.isTrue(delete == 1, () -> new BusinessException("删除交易申请确认函失败"));
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateTradeApplicationConfirmLetterByConfirmLetterId(LindiTradeApplicationConfirmLetterVO tradeApplicationConfirmLetterVO){
        LindiTradeApplicationConfirmLetter confirmLetter = mapper
                .selectTradeApplicationConfirmLetterByConfirmLetterId(
                        tradeApplicationConfirmLetterVO.getConfirmLetterId());
        Assert.notNull(confirmLetter, () -> new BusinessException("交易申请确认函不存在"));

        BeanUtil.copyProperties(tradeApplicationConfirmLetterVO, confirmLetter, CopyOptions.create().ignoreNullValue());
        confirmLetter.setUpdateTime(LocalDateTime.now());

        int update = mapper.update(confirmLetter);
        Assert.isTrue(update == 1, () -> new BusinessException("更新交易申请确认函失败"));
    }

    @Override
    public PageResp<LindiTradeApplicationConfirmLetterVO> getPageTradeApplicationConfirmLetterList(LindiTradeApplicationConfirmLetterQueryVO queryVO){
        // 分页查询
        Page<LindiTradeApplicationConfirmLetter> confirmLetterPage = mapper.selectPageTradeApplicationConfirmLetterList(queryVO);

        // 数据转换
        List<LindiTradeApplicationConfirmLetterVO> voList = BeanUtil.copyToList(confirmLetterPage.getRecords(), LindiTradeApplicationConfirmLetterVO.class);

        // 填充文件信息
        for (LindiTradeApplicationConfirmLetterVO vo : voList){
            if (vo.getFileId() != null){
                R<FileVO> fileResult = fileFeignClient.getFileByFileId(vo.getFileId());
                if (fileResult.getCode() == 200 && fileResult.getData() != null){
                    vo.setFile(fileResult.getData());
                }
            }
        }

        return new PageResp<>(voList, confirmLetterPage.getTotalRow());
    }

    @Override
    public LindiTradeApplicationConfirmLetterVO getTradeApplicationConfirmLetterByConfirmLetterId(Long confirmLetterId){
        LindiTradeApplicationConfirmLetter confirmLetter = mapper.selectTradeApplicationConfirmLetterByConfirmLetterId(confirmLetterId);
        Assert.notNull(confirmLetter, () -> new BusinessException("交易申请确认函不存在"));

        LindiTradeApplicationConfirmLetterVO vo = BeanUtil.copyProperties(confirmLetter, LindiTradeApplicationConfirmLetterVO.class);

        // 填充文件信息
        if (confirmLetter.getFileId() != null){
            R<FileVO> fileResult = fileFeignClient.getFileByFileId(confirmLetter.getFileId());
            if (fileResult.getCode() == HttpStatus.HTTP_OK && fileResult.getData() != null){
                vo.setFile(fileResult.getData());
            }
        }

        return vo;
    }

    @Override
    public LindiTradeApplicationConfirmLetterVO getTradeApplicationConfirmLetterByTradeApplicationId(Long tradeApplicationId){
        List<LindiTradeApplicationConfirmLetter> confirmLetterList = mapper
                .selectTradeApplicationConfirmLetterListByTradeApplicationId(tradeApplicationId);

        if (confirmLetterList.isEmpty()){
            return null;
        }

        // 获取最新的确认函（按创建时间排序后取第一个）
        LindiTradeApplicationConfirmLetter confirmLetter = confirmLetterList.get(0);
        LindiTradeApplicationConfirmLetterVO vo = BeanUtil.copyProperties(confirmLetter, LindiTradeApplicationConfirmLetterVO.class);

        // 填充文件信息
        if (confirmLetter.getFileId() != null){
            R<FileVO> fileResult = fileFeignClient.getFileByFileId(confirmLetter.getFileId());
            if (fileResult.getCode() == HttpStatus.HTTP_OK && fileResult.getData() != null){
                vo.setFile(fileResult.getData());
            }
        }

        return vo;
    }

    @Override
    public List<LindiTradeApplicationConfirmLetter> getTradeApplicationConfirmLetterListByConfirmLetterId(Long confirmLetterId){
        List<LindiTradeApplicationConfirmLetter> confirmLetterList = mapper.selectTradeApplicationConfirmLetterListByConfirmLetterId(confirmLetterId);
        Assert.notEmpty(confirmLetterList, () -> new BusinessException("交易申请确认函列表不存在"));
        return confirmLetterList;
    }

    @Override
    public List<LindiTradeApplicationConfirmLetterVO> getTradeApplicationConfirmLetterListByTradeApplicationId(Long tradeApplicationId){
        List<LindiTradeApplicationConfirmLetter> confirmLetterList = mapper
                .selectTradeApplicationConfirmLetterListByTradeApplicationId(tradeApplicationId);

        // 数据转换
        List<LindiTradeApplicationConfirmLetterVO> voList = BeanUtil.copyToList(confirmLetterList, LindiTradeApplicationConfirmLetterVO.class);

        // 填充文件信息
        for (LindiTradeApplicationConfirmLetterVO vo : voList){
            if (vo.getFileId() != null){
                R<FileVO> fileResult = fileFeignClient.getFileByFileId(vo.getFileId());
                if (fileResult.getCode() == HttpStatus.HTTP_OK && fileResult.getData() != null){
                    vo.setFile(fileResult.getData());
                }
            }
        }

        return voList;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public LindiTradeApplicationConfirmLetterVO generateConfirmLetter(Long tradeApplicationId
            , String confirmLetterType, Long createId, Long tenantId){
        return null;
//        // TODO: 实现确认函生成逻辑
//        // 1. 根据确认函类型获取模板信息
//        // 2. 根据交易申请ID获取交易申请信息
//        // 3. 使用模板和交易申请信息生成确认函文件
//        // 4. 保存确认函记录
//
//        Long fileId = confirmLetterTemplateManager.generateConfirmLetter(
//                tradeApplicationId, confirmLetterType, createId, tenantId);
//        LindiTradeApplicationConfirmLetter confirmLetter = new LindiTradeApplicationConfirmLetter();
//        confirmLetter.setConfirmLetterId(UnqIdUtil.uniqueId());
//        confirmLetter.setTradeApplicationId(tradeApplicationId);
//        confirmLetter.setConfirmLetterType(confirmLetterType);
//        confirmLetter.setFileId(fileId);
//        confirmLetter.setCreateId(createId);
//        confirmLetter.setUpdateId(createId);
//        LocalDateTime now = LocalDateTime.now();
//        confirmLetter.setCreateTime(now);
//        confirmLetter.setUpdateTime(now);
//
//        int insert = mapper.insert(confirmLetter, true);
//        Assert.isTrue(insert == 1, () -> new BusinessException("生成确认函失败"));
//
//        LindiTradeApplicationConfirmLetterVO lindiTradeApplicationConfirmLetterVO
//                = BeanUtil.copyProperties(confirmLetter, LindiTradeApplicationConfirmLetterVO.class);
//
//        R<FileVO> fileByFileId = fileFeignClient.getFileByFileId(fileId);
//        Assert.isTrue(fileByFileId.getCode() == HttpStatus.HTTP_OK
//                        && fileByFileId.getData() != null
//                , () -> new BusinessException("获取确认函文件失败"));
//        lindiTradeApplicationConfirmLetterVO.setConfirmLetterFile(fileByFileId.getData());
//        return lindiTradeApplicationConfirmLetterVO;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteTradeApplicationConfirmLetterFileByFileId(Long fileId){
        // 删除文件
        try{
            R<Void> result = fileFeignClient.deleteFile(fileId);
            if (result.getCode() != 200){
                logger.warn("删除确认函文件失败，文件ID: {}, 错误信息: {}", fileId, result.getMessage());
            }
        } catch (Exception e){
            logger.warn("删除确认函文件异常，文件ID: {}, 异常信息: {}", fileId, e.getMessage());
        }
    }

    /**
     * 生成确认函编号
     *
     * @return 确认函编号
     */
    private String generateConfirmLetterNumber(){
        return "QRH" + System.currentTimeMillis();
    }
}
